package com.mebs.edi.parser.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;


/**
 * 
 * This class allows generating XML file from a DOM Document object
 * 
 * @author nit
 * @version 1.0
 * 
 */
public class XmlGenerator {
	
	private static final Logger LOG = Logger.getLogger(XmlGenerator.class);
	
	public XmlGenerator() {
		LOG.debug("Instantiating XmlGenerator");
	}
	
	/**
	 * 
	 * Generates XML file using provided DOM Document object
	 * 
	 * @param document
	 * @param outputFile
	 * 
	 */
	public void generate(Document document, File outputFile) throws XmlGenerationException {
		LOG.info("Generating XML for: " + document + "; to: " + outputFile);
		try {
			// set up a transformer
	        TransformerFactory transfac = TransformerFactory.newInstance();
	        Transformer trans = transfac.newTransformer();
	        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
	        trans.setOutputProperty(OutputKeys.INDENT, "yes");     
	        
	        // StreamResult.PI_DISABLE_OUTPUT_ESCAPING
	        // TODO: escaping special characters (like ">") should be disabled somehow
	        // otherwise we end up with "&gt;" instead of ">" in ISA16 
	       
	        // TODO: write directly to FileOutputStream 
	        // once proper character escaping is implemented
	        // FileOutputStream fos = new FileOutputStream(outputFile);
	        StringWriter sw = new StringWriter();
	        StreamResult result = new StreamResult(sw);
	        
	        DOMSource source = new DOMSource(document);
	        trans.transform(source, result);
	        
	        String xmlString = sw.toString();
	        // this is ugly indeed. See the TODO marks above
	        xmlString = xmlString.replaceAll("&gt;", ">");
	        
	        FileWriter fw = new FileWriter(outputFile);
	        fw.write(xmlString);
	        fw.flush();
	        fw.close();
	        
	        LOG.info("Generating XML finished");

		} catch (Exception e) {
			throw new XmlGenerationException("Generating XML failed", e);
		}
	}
}
